def calculate_shares(total_cost, member_usages_dict):
    """根据用量比例计算分摊费用"""
    total_usage = sum(member_usages_dict.values())
    
    if total_usage == 0:
        # 总用量为0时的处理逻辑：平均分摊
        member_count = len(member_usages_dict)
        if member_count == 0:
            return {}
        share_per_person = total_cost / member_count
        return {name: share_per_person for name in member_usages_dict}
    
    # 按用量比例分摊
    shares = {}
    for name, usage in member_usages_dict.items():
        share = (usage / total_usage) * total_cost
        shares[name] = round(share, 2)  # 保留两位小数
    return shares

def calculate_and_display_bill_interaction(members_data, total_electricity_cost, total_water_cost):
    """计算并显示分摊账单的交互函数"""
    # 提取电费和水费的用量字典
    electricity_usages = {name: data["electricity"] for name, data in members_data.items()}
    water_usages = {name: data["water"] for name, data in members_data.items()}
    
    # 计算分摊费用
    electricity_shares = calculate_shares(total_electricity_cost, electricity_usages)
    water_shares = calculate_shares(total_water_cost, water_usages)
    
    # 显示账单
    print("\n===== 宿舍水电费分摊账单 =====")
    print(f"总电费: {total_electricity_cost} 元")
    print(f"总水费: {total_water_cost} 元")
    print("-----------------------------")
    print(f"{'姓名':<8}{'用电量(度)':<12}{'电费(元)':<10}{'用水量(吨)':<12}{'水费(元)':<10}{'总分摊(元)'}")
    print("-" * 60)
    
    members_share = []
    
    for name in members_data:
        electricity_usage = members_data[name]["electricity"]
        water_usage = members_data[name]["water"]
        electricity_share = electricity_shares.get(name, 0)
        water_share = water_shares.get(name, 0)
        total_share = electricity_share + water_share
        
        members_share.append({
            "name": name,
            "electricity_usage": electricity_usage,
            "water_usage": water_usage,
            "electricity_share": electricity_share,
            "water_share": water_share,
            "total_share": total_share
        })
        
        print(f"{name:<8}{electricity_usage:<12.2f}{electricity_share:<10.2f}{water_usage:<12.2f}{water_share:<10.2f}{total_share:<10.2f}")
    
    print("-" * 60)
    print(f"{'总计':<8}{sum(electricity_usages.values()):<12.2f}{total_electricity_cost:<10.2f}{sum(water_usages.values()):<12.2f}{total_water_cost:<10.2f}{total_electricity_cost + total_water_cost:<10.2f}")
    
    # 组装完整的账单对象
    bill_object = {
        "total_electricity_cost": total_electricity_cost,
        "total_water_cost": total_water_cost,
        "members_share": members_share
    }
    
    return bill_object    